﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using ESOL.Common.Entity;
using ESOL.Business.Proj;
using ESOL.Business.Bpt;
using DevExpress.XtraTreeList.Nodes;
using ESOL.Business.Mst;
using ESOL.WinUI.MasterData;
using DevExpress.Utils.Drawing;
using ESOL.Common;
using ESOL.WinUI.Bpt;

namespace ESOL.WinUI.Proj
{
    public partial class frmMaintainMBOM : BaseForm.frmBaseDialogyBusinessForm
    {
        #region vars
        public MstProductEntity SelectedProduct { set; get; }
        public BomProductBomMasterEntity SelectedProductBomMaster { set; get; }
        private BptBlueprintEntity mSelectedBlueprint;
        private string sSelectedBomID;
        private List<BomProductBomMasterEntity> listDeleteProductBomMaster = new List<BomProductBomMasterEntity>();
        private DataRow drSelectedNode;
        #endregion

        #region ctors
        public frmMaintainMBOM()
        {
            InitializeComponent();
        }
        #endregion

        #region functions
        private void BindCombobox()
        {
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbItemType, "PDTYPE", false);
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbStatus, "BOM_S", false);
            UICommon.UICommonFunctions.BindComboboxByEnum(cmbCustomerFor, typeof(IsCustomerForFlag), typeof(int), false);

            UICommon.UICommonFunctions.BindGridComboboxByCommonItem(rcolItemType, "PDTYPE", false);
            UICommon.UICommonFunctions.BindGridComboboxByCommonItem(rcolValidStatus, "BOM_S", false);
            UICommon.UICommonFunctions.BindGridComboboxByEnum(rcolCustomerForFlag, typeof(IsCustomerForFlag), typeof(int), false);
            UICommon.UICommonFunctions.BindGridComboboxByEnum(rcolApproveStatus, typeof(BomApproveStatus), typeof(int), false);
        }

        private void SetField()
        {
            if (ThisActionType == ActionType.New)
            {
                LoadBomByBlueprint();
            }
            else if (ThisActionType == ActionType.Modify
                || ThisActionType == ActionType.View || ThisActionType == ActionType.Approve)
            {
                LoadBomByBomMaster();
            }
        }

        private void LoadBomByBlueprint()
        {
            if (SelectedProduct == null)
            {
                MessageBox.Show("物料不存在！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            mSelectedBlueprint = BptBlueprintBs.GetBptBlueprintByProductID(SelectedProduct.ProductId);
            if (mSelectedBlueprint == null)
            {
                MessageBox.Show("物料不存在！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            DataTable dt = ProjMBOMBs.GetDtBlueprintBomByBlueprintID(mSelectedBlueprint.BlueprintId);
            tlMain.DataSource = dt;
        }

        private void LoadBomByBomMaster()
        {
            if (SelectedProductBomMaster == null)
            {
                MessageBox.Show("物料BOM不存在！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            //DataTable dt = BomProductBomMasterBs.GetDtProductBomByProductID(SelectedProduct.ProductId, "PDTYPE01","");
            DataTable dt = ProjMBOMBs.GetDtProductBomByBomID(SelectedProductBomMaster.BomId, "", "");
            tlMain.DataSource = dt;
        }

        private bool CheckData()
        {
            DataTable dt = tlMain.DataSource as DataTable;
            if (dt.Rows.Count == 0)
            {
                MessageBox.Show("明细不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            string sCurVersion = dt.Rows[0]["VERSION"].ToString();
            if (SelectedProductBomMaster != null)
            {
                if (SelectedProductBomMaster.Version.Equals(sCurVersion))
                {
                    return true;
                }
            }
            if (ProjMBOMBs.IsExistVersion(SelectedProduct.ProductId, sCurVersion))
            {
                MessageBox.Show("版本号已存在，请修改！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            return true;
        }

        private void SetMaterial()
        {
            if (drSelectedNode == null)
                return;
            MstProductEntity entity = MstProductBs.GetMstProductTypeByID(drSelectedNode["PRODUCT_ID"].ToString());
            if (entity == null)
                return;
            frmMaintainMBOMMaterial frm = new frmMaintainMBOMMaterial(entity);
            frm.ShowDialog();
        }

        private void SetTechnic()
        {
            if (drSelectedNode == null)
                return;
            MstProductEntity entity = MstProductBs.GetMstProductTypeByID(drSelectedNode["PRODUCT_ID"].ToString());
            frmMaintainMBOMTechnic frm = new frmMaintainMBOMTechnic(entity);
            frm.ShowDialog();
        }
        #endregion

        #region events
        protected override void OnShown(EventArgs e)
        {
            base.OnShown(e);
            BindCombobox();
            SetField();
            tlMain.ExpandAll();
        }

        private void tlMain_CustomDrawNodeIndicator(object sender, DevExpress.XtraTreeList.CustomDrawNodeIndicatorEventArgs e)
        {
            ESOL.Controls.DevTreeList tree = sender as ESOL.Controls.DevTreeList;
            IndicatorObjectInfoArgs args = e.ObjectArgs as IndicatorObjectInfoArgs;
            args.DisplayText = (tree.GetVisibleIndexByNode(e.Node) + 1).ToString();
        }

        private void tlMain_AfterDragNode(object sender, DevExpress.XtraTreeList.NodeEventArgs e)
        {
            DataTable dt = (DataTable)tlMain.DataSource;
            string sSelectedNode = e.Node.GetValue("BOM_ID").ToString();
            string sTargetNode = e.Node.ParentNode.GetValue("BOM_ID").ToString();
            DataRow drSelectedNode = dt.Select("BOM_ID='" + sSelectedNode + "'")[0];
            drSelectedNode["PARENT_BOM_ID"] = sTargetNode;
        }

        private void tlMain_FocusedNodeChanged(object sender, DevExpress.XtraTreeList.FocusedNodeChangedEventArgs e)
        {
            if (e.Node != null)
            {
                DataTable dt = (DataTable)tlMain.DataSource;
                sSelectedBomID = e.Node.GetValue("BOM_ID").ToString();
                drSelectedNode = dt.Select("BOM_ID='" + sSelectedBomID + "'")[0];
                txtVersion.Text = e.Node.GetValue("VERSION").ToString();
                if (string.IsNullOrEmpty(drSelectedNode["ITEM_TYPE"].ToString()) == false)
                {
                    cmbItemType.SetSelectedValue(drSelectedNode["ITEM_TYPE"]);
                }
                txtSequence.Text = drSelectedNode["SEQENCE"].ToString();
                txtUnitDose.Text = drSelectedNode["UNIT_DOSE"].ToString();
                if (string.IsNullOrEmpty(drSelectedNode["STATUS"].ToString()) == false)
                {
                    cmbStatus.SetSelectedValue(drSelectedNode["STATUS"].ToString());
                }
                if (string.IsNullOrEmpty(drSelectedNode["IS_CUSTOMER_FOR"].ToString()) == false)
                {
                    cmbCustomerFor.SetSelectedValue(drSelectedNode["IS_CUSTOMER_FOR"].ToString());
                }
                if (string.IsNullOrEmpty(drSelectedNode["LOSS_RATE"].ToString()) == false)
                {
                    txtLoseRate.Text = drSelectedNode["LOSS_RATE"].ToString();
                }
                if (string.IsNullOrEmpty(drSelectedNode["CONSTANT_SCRAP"].ToString()) == false)
                {
                    txtConstantScrap.Text = drSelectedNode["CONSTANT_SCRAP"].ToString();
                }
                if (string.IsNullOrEmpty(drSelectedNode["EFFECTIVE_DATE"].ToString()) == false)
                {
                    dtpEffectiveDate.EditValue = Convert.ToDateTime(drSelectedNode["EFFECTIVE_DATE"].ToString());
                }
                if (string.IsNullOrEmpty(drSelectedNode["EXPIRATION_DATE"].ToString()) == false)
                {
                    dtpEffectiveDateTo.EditValue = Convert.ToDateTime(drSelectedNode["EXPIRATION_DATE"].ToString());
                }
                if (string.IsNullOrEmpty(drSelectedNode["SUPPLIER_ID"].ToString()) == false)
                {

                }
                txtRemark.Text = drSelectedNode["REMARK"].ToString();
            }
        }

        private void txtVersion_EditValueChanged(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtVersion.Text) == false)
            {
                drSelectedNode["VERSION"] = txtVersion.Text.Trim();
            }
            else
            {
                MessageBox.Show("版本不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                txtVersion.Focus();
                return;
            }
        }

        private void txtSequence_EditValueChanged(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtSequence.Text) == false)
            {
                drSelectedNode["SEQENCE"] = txtSequence.Text;
            }
            else
            {
                MessageBox.Show("序号不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                txtSequence.Focus();
                return;
            }
        }

        private void txtUnitDose_EditValueChanged(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtUnitDose.Text) == false)
            {
                drSelectedNode["UNIT_DOSE"] = Convert.ToDecimal(txtUnitDose.Text);
            }
            else
            {
                MessageBox.Show("单位用量不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                txtUnitDose.Focus();
                return;
            }
        }

        private void cmbItemType_SelectionChangeCommitted(object sender, EventArgs e)
        {
            DataTable dt = tlMain.DataSource as DataTable;
            int nIndex = dt.Rows.IndexOf(drSelectedNode);
            if (nIndex == 0 && cmbItemType.SelectedValue.ToString().Equals("PDTYPE02"))
            {
                MessageBox.Show("首节点物料类型不可为空外购！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            drSelectedNode["ITEM_TYPE"] = cmbItemType.SelectedValue.ToString();
        }

        private void cmbCustomerFor_SelectionChangeCommitted(object sender, EventArgs e)
        {
            drSelectedNode["IS_CUSTOMER_FOR"] = Convert.ToInt32(cmbCustomerFor.SelectedValue);
        }

        private void cmbStatus_SelectionChangeCommitted(object sender, EventArgs e)
        {
            drSelectedNode["STATUS"] = cmbStatus.SelectedValue;
        }

        private void tsmNewLine_Click(object sender, EventArgs e)
        {
            if (tlMain.DataSource == null)
            {
                return;
            }
            DataTable dt = tlMain.DataSource as DataTable;
            DataRow dr = dt.NewRow();
            dr["BOM_ID"] = Guid.NewGuid().ToString();
            dr["VERSION"] = "1.0";
            dr["SEQENCE"] = "1";
            dr["UNIT_DOSE"] = 0;
            dr["ITEM_TYPE"] = "PDTYPE01";
            dr["STATUS"] = "BOM_S01";
            dr["IS_CUSTOMER_FOR"] = 0;
            dt.Rows.Add(dr);
        }

        private void tsmDelLine_Click(object sender, EventArgs e)
        {
            if (drSelectedNode == null)
            {
                return;
            }
            DataTable dt = tlMain.DataSource as DataTable;
            dt.Rows.Remove(drSelectedNode);
        }

        private void tsmMaterialSet_Click(object sender, EventArgs e)
        {
            SetMaterial();
        }

        private void tsmTechnicSet_Click(object sender, EventArgs e)
        {
            SetTechnic();
        }

        private void bbtnMaterial_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            SetMaterial();
        }

        private void bbtnTechnic_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            SetTechnic();
        }

        private void bbtnExpert_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            SaveFileDialog frm = new SaveFileDialog();
            frm.Filter = "All Files (*.*)|";
            frm.DefaultExt = "xls";
            frm.AddExtension = true;
            frm.FileName = "物料清单导出列表" + DateTime.Today.ToString("yyyy-MM-dd");
            if (frm.ShowDialog() == DialogResult.OK)
            {
                tlMain.ExportToXls(frm.FileName);
            }     
        }

        protected override void Click_Save()
        {
            if (CheckData() == false)
                return;
            DataTable dt = (DataTable)tlMain.DataSource;
            if (ProjMBOMBs.SaveProductBom(dt, listDeleteProductBomMaster))
            {
                MessageBox.Show("保存成功！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                DialogResult = DialogResult.OK;
            }
            else
            {
                MessageBox.Show("保存失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        protected override void Click_Approve()
        {
            if (SelectedProductBomMaster == null)
            {
                MessageBox.Show("物料清单为空！","Information",MessageBoxButtons.OK,MessageBoxIcon.Information);
                return;
            }
            SelectedProductBomMaster.ApproveStatus = (int)BomApproveStatus.已审核;
            if (ProjMBOMBs.UpdateBomProductBomMaster(SelectedProductBomMaster))
            {
                MessageBox.Show("审核成功！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                DialogResult = DialogResult.OK;
            }
            else
            {
                MessageBox.Show("审核失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
        }

        protected override void Click_Reject()
        {
            if (SelectedProductBomMaster == null)
            {
                MessageBox.Show("物料清单为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            SelectedProductBomMaster.ApproveStatus = (int)BomApproveStatus.已拒绝;
            if (ProjMBOMBs.UpdateBomProductBomMaster(SelectedProductBomMaster))
            {
                MessageBox.Show("拒审成功！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                DialogResult = DialogResult.OK;
            }
            else
            {
                MessageBox.Show("拒审失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
        }

        private void repositoryItemButtonEdit1_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (drSelectedNode == null)
            {
                return;
            }
            frmMaintainProductQuery frm = new frmMaintainProductQuery();
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedProduct != null)
            {
                drSelectedNode["PRODUCT_ID"] = frm.SelectedProduct.ProductId;
                drSelectedNode["PRODUCT_NAME"] = frm.SelectedProduct.ProductName;
                drSelectedNode["PRODUCT_CODE"] = frm.SelectedProduct.ProductCode;
                drSelectedNode["DESCRIPTION"] = frm.SelectedProduct.Description;
            }
        }

        #endregion
    }
}
